import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CustomerSimpleManage } from './entities/customer-simple-manage.entity';
import { ResponseService } from 'src/response/response.service';
import { SimplePaginatedResponse } from 'src/common/dto/pagination.dto';

@Injectable()
export class CustomerSimpleManageService {
  constructor(
    @InjectRepository(CustomerSimpleManage)
    private customerSimpleManageRepository: Repository<CustomerSimpleManage>,
    private readonly responseService: ResponseService
  ) { }

  findAll(): Promise<CustomerSimpleManage[]> {
    return this.customerSimpleManageRepository.find({
      relations: ['children'],
      order: {
        date: 'DESC',
      },
    });
  }

  findOne(id: number): Promise<CustomerSimpleManage> {
    return this.customerSimpleManageRepository.findOne({
      where: { _Identify: id },
      relations: ['children'],
    });
  }

  async remove(id: number): Promise<void> {
    await this.customerSimpleManageRepository.delete(id);
  }

  async findWithPagination(
    page: number,
    conditions: Partial<CustomerSimpleManage>,
  ): Promise<{ data: CustomerSimpleManage[]; total: number }> {
    const take = 30; // 每页30条
    const skip = (page - 1) * take;

    const [data, total] =
      await this.customerSimpleManageRepository.findAndCount({
        where: conditions,
        take,
        skip,
        relations: ['children'], // 如果你想加载关联表数据
        order: {
          date: 'DESC',
        },
      });

    return { data, total };
  }

  async searchByKeyword(
    keyword: string,
    page: number = 1,
    limit: number = 50,
  ): Promise<SimplePaginatedResponse<CustomerSimpleManage>> {
    // 确保参数在有效范围内
    const pageNum = Math.max(1, Math.min(page, 2147483647));
    const pageSize = Math.max(1, Math.min(limit, 1000));
    const skip = (pageNum - 1) * pageSize;

    // 查询数据和总数
    const [data, total] = await this.customerSimpleManageRepository
      .createQueryBuilder('manage')
      // 连接 customer_simple_child 表
      .leftJoinAndSelect('manage.children', 'child')
      .where('customername LIKE :keyword', { keyword: `%${keyword}%` })
      .orWhere('manage.manageid LIKE :keyword', { keyword: `%${keyword}%` })
      // 按 date 倒序排列
      .orderBy('manage.date', 'DESC')
      // 分页
      .take(pageSize)
      .skip(skip)
      .getManyAndCount(); // 使用 getManyAndCount 返回数据和总数

    // 返回统一的分页格式
    return {
      data,
      total,
      page: pageNum,
      limit: pageSize,
    };
  }
}
